package com.braveman.im.ui.fragment;

import android.Manifest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.braveman.im.R;
import com.braveman.im.bean.FriendGroupNameBean;
import com.braveman.im.bean.FriendsComentsBean;
import com.braveman.im.bean.FriendshipListBean;
import com.braveman.im.bean.JsonBean;
import com.braveman.im.bean.JsonNewBean;
import com.braveman.im.bean.Moment;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.ui.activity.message.SendLoveActivity;
import com.braveman.im.ui.adapter.FriendsGroupNameAdapter;
import com.braveman.im.ui.adapter.PhotoAdapter;
import com.braveman.im.ui.adapter.PhotoAdapterNew;
import com.braveman.im.ui.weiget.DiaogPopup;
//import com.braveman.im.ui.weiget.TextMoreTextView;
import com.braveman.im.ui.weiget.RecyclerItemClickListener;
import com.braveman.im.ui.weiget.TextMoreTextView;
import com.braveman.im.utils.GetJsonDataUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseFragment;
import com.ht.baselibs.ui.widget.LoadingLayout;
import com.ht.baselibs.utils.NetUtils;
import com.ht.baselibs.utils.UIUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import java.util.zip.Inflater;

import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.imageloader.BGAImage;
import cn.bingoogolapple.photopicker.imageloader.BGAImageLoader;
import cn.bingoogolapple.photopicker.util.BGAAsyncTask;
import cn.bingoogolapple.photopicker.util.BGAPhotoPickerUtil;
import cn.bingoogolapple.photopicker.util.BGASavePhotoTask;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Response;

public class CircleFriendsFragment extends BaseFragment implements BGANinePhotoLayout.Delegate, EasyPermissions.PermissionCallbacks, BGAAsyncTask.Callback<Void> {
    public static final int TAG_CREATE = 0x01;
    public static final int TAG_DELETE = 0x02;
    public static final int TAG_MODIFY = 0x03;

    private static final int REQUEST_CODE_PERMISSION_PHOTO_PREVIEW = 1;

    private static final int REQUEST_CODE_ADD_MOMENT = 1;

    private ListView listView;
    private BGASavePhotoTask mSavePhotoTask;

    private BGANinePhotoLayout mCurrentClickNpl;
    private List<Moment> moments = new ArrayList<>();
    File downloadDir = new File(Environment.getExternalStorageDirectory(), "HSS");

    Stack stack = new Stack();
    private MyListAdpter myListAdpter;
    private LoadingLayout loadingLayout;
    private SmartRefreshLayout pLvMemberManager;
    private int currentPage;
    private TextView mTvFragCircleFriendsAddress;
    private TextView mTvFragCircleFriendsIndustry;
    private TextView mTvFragCircleFriendsInterests;
    private TextView mTvFragCircleFriendsNativePlace;
    private RecyclerView mTvFragCircleFriendsList;
    private DiaogPopup diaogPopup;
    private PhotoAdapterNew photoAdapter;

    private ArrayList<JsonNewBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private String[] industys = {"信息技术", "商业服务", "汽车摩电", "金融保险", "工业制造", "工业制造", "交通运输", "文化传媒", "公共事业", "农林牧渔", "房产/建筑/家居业"};
    private String[] hobbys = {"运动", "棋类", "旅游", "登山", "乐器", "音乐", "舞蹈", "饮茶", "影视", "阅读", "赋诗", "书法", "写作", "社交", "健身"};

    private boolean isLoaded = false;
    private JsonNewBean.ChildBeanX.ChildBean childBean = new JsonNewBean.ChildBeanX.ChildBean();
    public String residenceId = "";//居住城市id
    public String interestCategoryId = "";//兴趣爱好id
    public String corpIndustryId = "";//公司所属行业id
    public String birthpalceId = "";//籍贯id
    public String userFriendCategoryId = "";//好友分组id
    public int pageNo = 1;
    public int pageSiz = 10;
    private List<FriendGroupNameBean> listFroFriendsGroup = new ArrayList<>();//好友分组列表
    private FriendsGroupNameAdapter friendsGroupNameAdapter;

    @Override
    public void onDestroy() {
        if (mSavePhotoTask != null) {
            mSavePhotoTask.cancelTask();
            mSavePhotoTask = null;
        }
        super.onDestroy();
    }

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {

    }

    @Override
    protected View initContentView() {
        return LayoutInflater.from(mContext).inflate(R.layout.frag_circle_friends, null);
    }

    @Override
    protected void initChildView() {
        listView = findViewById(R.id.recy_central_document_frag);
        View headerView = View.inflate(mContext, R.layout.head_view_frag_circle_friends, null);
        mTvFragCircleFriendsList = headerView.findViewById(R.id.tv_frag_circle_friends_list);
        SnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(mTvFragCircleFriendsList);//这里放置的是的recycleview
        listView.addHeaderView(headerView);
        pLvMemberManager = findViewById(R.id.plv_activity_member_manager);
        mTvFragCircleFriendsAddress = headerView.findViewById(R.id.tv_frag_circle_friends_address);
        mTvFragCircleFriendsIndustry = headerView.findViewById(R.id.tv_frag_circle_friends_industry);
        mTvFragCircleFriendsInterests = headerView.findViewById(R.id.tv_frag_circle_friends_interests);
        mTvFragCircleFriendsNativePlace = headerView.findViewById(R.id.tv_frag_circle_friends_native_place);
        pLvMemberManager.setRefreshFooter(new ClassicsFooter(mContext).setSpinnerStyle(SpinnerStyle.Scale));
        loadingLayout = findViewById(R.id.loading_layout);
        moments = new ArrayList<>();
        currentPage = 1;
        myListAdpter = new MyListAdpter(mContext, moments);
        listView.setAdapter(myListAdpter);
        loadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadingLayout.setStatus(LoadingLayout.Loading);
                currentPage = 1;
                load();
            }
        });
        pLvMemberManager.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                currentPage = 1;
                if (!NetUtils.isNetWorkConnection()) {
                    UIUtils.showToast("请检查您的网络设置");
                    return;
                }
                //pLvMemberManager.resetHasMore();
                pLvMemberManager.setLoadmoreFinished(false);
                currentPage = 1;
                load();
            }
        });
        pLvMemberManager.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                currentPage++;
                load();
            }
        });
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mTvFragCircleFriendsList.setLayoutManager(linearLayoutManager);
        //设置适配器
        friendsGroupNameAdapter = new FriendsGroupNameAdapter(R.layout.item_friends_group_name_list, listFroFriendsGroup);


    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        Toast.makeText(mContext, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    Toast.makeText(mContext, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(mContext, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    @Override
    protected void load() {
        ApiManager.getApi().friendsMoments(residenceId, interestCategoryId, corpIndustryId, birthpalceId, userFriendCategoryId, pageNo, pageSiz)
                .enqueue(new NetCallBack<FriendsComentsBean>() {
                    @Override
                    protected void onSuccess(Call<FriendsComentsBean> call, Response<FriendsComentsBean> response) {
                        getFriendsList();
                        if (response != null) {
                            FriendsComentsBean friendsComentsBean = response.body();

                            if (friendsComentsBean != null) {

                                for (FriendsComentsBean.DataListBean dataListBean : friendsComentsBean.dataList) {
                                    Moment moment = new Moment(dataListBean.content, dataListBean.photoList);
                                    moments.add(moment);
                                }
                            }
                        }
                        loadingLayout.setStatus(LoadingLayout.Success);

                    }
                });
    }

    private void getFriendsList() {
        ApiManager.getApi().getFriendGroupName().enqueue(new NetCallBack<List<FriendGroupNameBean>>() {
            @Override
            protected void onSuccess(Call<List<FriendGroupNameBean>> call, Response<List<FriendGroupNameBean>> response) {
                if (response != null) {
                    if (listFroFriendsGroup != null && listFroFriendsGroup.size() > 0) {
                        listFroFriendsGroup.clear();
                    }
                    listFroFriendsGroup = response.body();
                    friendsGroupNameAdapter = new FriendsGroupNameAdapter(R.layout.item_friends_group_name_list, listFroFriendsGroup);
                    mTvFragCircleFriendsList.setAdapter(friendsGroupNameAdapter);
                    if (friendsGroupNameAdapter != null) {
                        friendsGroupNameAdapter.notifyDataSetChanged();
                    }
                }
            }
        });

    }


    @Override
    protected void setChildViewListener() {
        mTvFragCircleFriendsAddress.setOnClickListener(this);
        mTvFragCircleFriendsIndustry.setOnClickListener(this);
        mTvFragCircleFriendsInterests.setOnClickListener(this);
        mTvFragCircleFriendsNativePlace.setOnClickListener(this);
        findViewById(R.id.tv_frag_friends_changes).setOnClickListener(this);

        friendsGroupNameAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.name:
                        userFriendCategoryId = listFroFriendsGroup.get(position).id;
                        int mostSize = listFroFriendsGroup.size();
                        for (int i = 0; i < mostSize; i++) {
                            if (i == position) {
                                listFroFriendsGroup.get(i).isChecked = true;
                            } else {
                                listFroFriendsGroup.get(i).isChecked = false;
                            }
                        }
                        friendsGroupNameAdapter = new FriendsGroupNameAdapter(R.layout.item_friends_group_name_list, listFroFriendsGroup);
                        mTvFragCircleFriendsList.setAdapter(friendsGroupNameAdapter);
                        break;
                }
            }
        });


        friendsGroupNameAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                userFriendCategoryId = listFroFriendsGroup.get(position).id;


            }
        });
    }

    @Override
    public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
        mCurrentClickNpl = ninePhotoLayout;
        photoPreviewWrapper();
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PREVIEW) {
            Toast.makeText(mContext, "您拒绝了「图片预览」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPostExecute(Void aVoid) {
        mSavePhotoTask = null;
        if (stack != null && !stack.isEmpty()) {
            savePic((String) stack.pop());
        } else {
            UIUtils.showToast("保存成功");
        }
    }

    @Override
    public void onTaskCancelled() {
        mSavePhotoTask = null;

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        reSelect();
        switch (v.getId()) {
            case R.id.tv_frag_circle_friends_address:
                mTvFragCircleFriendsAddress.setSelected(true);
                mTvFragCircleFriendsAddress.setText("地域");
                if (isLoaded) {
                    ShowPickerView(mTvFragCircleFriendsAddress);
                } else {
                    Toast.makeText(mContext, "请重试", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_frag_circle_friends_industry:
                DiaogPopup.Builder builder = new DiaogPopup.Builder(mContext);
                int count = 0;
                for (String industy : industys) {
                    builder.addItem(count++, industy);
                }
                diaogPopup = builder.build();
                diaogPopup.setOnListPopupItemClickListener(new DiaogPopup.OnListPopupItemClickListener() {
                    @Override
                    public void onItemClick(int what) {
                        mTvFragCircleFriendsIndustry.setText(industys[what]);
                        if (diaogPopup != null) {
                            diaogPopup.dismiss();
                        }
                    }
                });
                mTvFragCircleFriendsIndustry.setSelected(true);
                mTvFragCircleFriendsIndustry.setText("行业");
                diaogPopup.showPopupWindow(mTvFragCircleFriendsIndustry);//popuwindow特效

                break;
            case R.id.tv_frag_circle_friends_interests:
                mTvFragCircleFriendsInterests.setSelected(true);
                DiaogPopup.Builder builder1 = new DiaogPopup.Builder(mContext);
                int count1 = 0;
                for (String hobby : hobbys) {
                    builder1.addItem(count1++, hobby);
                }
                diaogPopup = builder1.build();
                diaogPopup.setOnListPopupItemClickListener(new DiaogPopup.OnListPopupItemClickListener() {
                    @Override
                    public void onItemClick(int what) {
                        mTvFragCircleFriendsInterests.setText(hobbys[what]);
                        if (diaogPopup != null) {
                            diaogPopup.dismiss();
                        }
                    }
                });
                mTvFragCircleFriendsInterests.setText("爱好");
                diaogPopup.showPopupWindow(mTvFragCircleFriendsInterests);
                break;
            case R.id.tv_frag_circle_friends_native_place:
                mTvFragCircleFriendsNativePlace.setSelected(true);
                mTvFragCircleFriendsNativePlace.setText("籍贯");
                if (isLoaded) {
                    ShowPickerView(mTvFragCircleFriendsNativePlace);
                } else {
                    Toast.makeText(mContext, "请重试", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_frag_friends_changes:
                load();
                break;
        }
    }

    private void reSelect() {
        mTvFragCircleFriendsAddress.setSelected(false);
        mTvFragCircleFriendsIndustry.setSelected(false);
        mTvFragCircleFriendsInterests.setSelected(false);
        mTvFragCircleFriendsNativePlace.setSelected(false);

    }

    private synchronized void savePic(final String url) {
        if (mSavePhotoTask != null) {
            return;
        }
        File file;
        if (url.startsWith("file")) {
            file = new File(url.replace("file://", ""));
            if (file.exists()) {
                UIUtils.showToast("");
                return;
            }
        }

        // 通过MD5加密url生成文件名，避免多次保存同一张图片
        file = new File(downloadDir, BGAPhotoPickerUtil.md5(url) + ".png");
        if (file.exists()) {
            UIUtils.showToast("图片已存在");
            return;
        }

        mSavePhotoTask = new BGASavePhotoTask(this, mContext, file);


        BGAImage.download(url, new BGAImageLoader.DownloadDelegate() {
            @Override
            public void onSuccess(String url, Bitmap bitmap) {
                mSavePhotoTask.setBitmapAndPerform(bitmap);

            }

            @Override
            public void onFailed(String url) {
                mSavePhotoTask = null;
                BGAPhotoPickerUtil.show(R.string.bga_pp_save_img_failure);
            }
        });
    }


    class MyListAdpter extends BaseAdapter {
        Context con;
        TextMoreTextView tv;
        List<Moment> data;

        public MyListAdpter(Context con, List<Moment> data) {
            this.con = con;
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        HashMap<Integer, View> hashM = new HashMap<Integer, View>();

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Holder holder = null;
            View view;
            if (hashM.get(position) == null) {
                holder = new Holder();
                view = LayoutInflater.from(con).inflate(R.layout.item_central_document,
                        null);
                holder.tv = (TextMoreTextView) view
                        .findViewById(R.id.tv_item_central_document_copy_text);

                holder.saveImgBtn = (Button) view.findViewById(R.id.btn_item_central_document_save_img);
                holder.copyTextBtn = (Button) view.findViewById(R.id.btn_item_central_document_copy_text);
                holder.mTvTimeDay = (TextView) view.findViewById(R.id.tv_time_day);
                holder.mTvTimeMonth = (TextView) view.findViewById(R.id.tv_time_month);
                holder.mTvTimeHour = (TextView) view.findViewById(R.id.tv_time_hour);
                holder.recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);


//                mTvTimeBefore = (TextView) findViewById(R.id.tv_time_before);
//                mTvDelete = (TextView) findViewById(R.id.tv_delete);
//                mIvCircleIconComment = (ImageView) findViewById(R.id.iv_circle_icon_comment);
//                mIvCircleDetailIconZan = (ImageView) findViewById(R.id.iv_circle_detail_icon_zan);
//                mIvCircleIconShare = (ImageView) findViewById(R.id.iv_circle_icon_share);




//            holder.ninePhotoLayout = (BGANinePhotoLayout) view.findViewById(R.id.npl_item_moment_photos);


                holder.saveImgBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (stack != null) {
                            stack.clear();
                        }
                        ArrayList<String> photos = moments.get(position).photos;
                        for (String photo : photos) {
                            stack.push(photo);
                        }
                        if (photos.size() > 0) {
                            UIUtils.showToast("正在保存...");
                            savePic(photos.get(0));
                            stack.remove(0);
                        }
                    }
                });
                holder.copyTextBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                        // 将文本内容放到系统剪贴板里。
                        cm.setText(moments.get(position).content);
                        UIUtils.showToast("已复制");
                    }
                });
                view.setTag(holder);
                hashM.put(position, view);
            } else {
                view = hashM.get(position);
                holder = (Holder) view.getTag();
            }

            photoAdapter = new PhotoAdapterNew(mContext, data.get(position).photos);
            holder.recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, OrientationHelper.VERTICAL));
            holder.recyclerView.setAdapter(photoAdapter);
            holder.recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(mContext,
                    new RecyclerItemClickListener.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int positiona) {
                            PhotoPreview.builder()
                                    .setPhotos(data.get(position).photos)
                                    .setCurrentItem(positiona)
                                    .start(mContext);
                        }
                    }));


            holder.tv.setDesc(data.get(position).content, holder.tv, TextView.BufferType.NORMAL);
            String time = data.get(position).time;
            if (!TextUtils.isEmpty(time)) {
                String day = time.substring(6, 8);
                String month = time.substring(3, 5);
                String hour = time.substring(8, 14);
                holder.mTvTimeDay.setText(day);
                holder.mTvTimeMonth.setText(month + "月");
                holder.mTvTimeHour.setText(hour);
            }
            return view;
        }

        class Holder {
            TextMoreTextView tv;
            //            BGANinePhotoLayout ninePhotoLayout;
            Button saveImgBtn;
            Button copyTextBtn;
            TextView mTvTimeDay, mTvTimeMonth, mTvTimeHour;
            RecyclerView recyclerView;
            TextView mTvTimeBefore;
            TextView mTvDelete;
             ImageView mIvCircleIconComment;
             ImageView mIvCircleDetailIconZan;
             ImageView mIvCircleIconShare;

        }
    }

    /**
     * 图片预览，兼容6.0动态权限
     */
    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PREVIEW)
    private void photoPreviewWrapper() {
        if (mCurrentClickNpl == null) {
            return;
        }
        // 保存图片的目录，改成你自己要保存图片的目录。如果不传递该参数的话就不会显示右上角的保存按钮

        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            if (mCurrentClickNpl.getItemCount() == 1) {
                // 预览单张图片

                startActivity(BGAPhotoPreviewActivity.newIntent(mContext, downloadDir, mCurrentClickNpl.getCurrentClickItem()));
            } else if (mCurrentClickNpl.getItemCount() > 1) {
                // 预览多张图片

                startActivity(BGAPhotoPreviewActivity.newIntent(mContext, downloadDir, mCurrentClickNpl.getData(), mCurrentClickNpl.getCurrentClickItemPosition()));
            }
        } else {
            EasyPermissions.requestPermissions(this, "图片预览需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PREVIEW, perms);
        }
    }

    private void ShowPickerView(final TextView textView) {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options2Items.get(options1).get(options2).name;
//                        +
//                        options3Items.get(options1).get(options2).get(options3);
                textView.setText(tx);
                String id = options2Items.get(options1).get(options2).id;
                UIUtils.showToast(id + "");
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

//        /*pvOptions.setPicker(options1Items);//一级选择器

//        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(mContext, "province_new.json");//获取assets目录下的json文件数据

        ArrayList<JsonNewBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<JsonNewBean.ChildBeanX.ChildBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).child.size(); c++) {//遍历该省份的所有城市
                JsonNewBean.ChildBeanX.ChildBean childBean = new JsonNewBean.ChildBeanX.ChildBean();
                childBean.name = jsonBean.get(i).child.get(c).name;
                childBean.id = jsonBean.get(i).child.get(c).id;
                CityList.add(childBean);//添加城市

                ArrayList<JsonNewBean.ChildBeanX.ChildBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).child.get(c).name == null
                        || jsonBean.get(i).child.get(c).child.size() == 0) {
                    City_AreaList.add(new JsonNewBean.ChildBeanX.ChildBean());
                } else {

                    for (int d = 0; d < jsonBean.get(i).child.get(c).child.size(); d++) {//该城市对应地区所有数据
                        JsonNewBean.ChildBeanX.ChildBean childBean1 = new JsonNewBean.ChildBeanX.ChildBean();
                        childBean1.name = jsonBean.get(i).child.get(c).child.get(d).name;
                        childBean1.id = jsonBean.get(i).child.get(c).child.get(d).id;
                        City_AreaList.add(childBean1);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonNewBean> parseData(String result) {//Gson 解析
        ArrayList<JsonNewBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonNewBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonNewBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

}
